import os, glob
import SCons.Defaults

# import root environment
Import( ["buildenv", "installer"])
myenv = buildenv.Copy()
# get all the sourcefiles recursively
cpps = myenv.SGlob("*.cc", excludedirs=["test"], recursive=True )
# need this to go to the root dir, as SConsript asumes to be in the
# build dir
rootdir = myenv.Dir("#").abspath
libname = myenv["PACKAGE"]

if "static" in myenv["libtype"]:
    # build static lib
    slib =  myenv.StaticLibrary(target = libname, source = [cpps])
    installer.AddLibrary(slib)
if "shared" in myenv["libtype"]:
    #build dynamic lib
    dlib =  myenv.SharedLibrary(target = libname, source = cpps)
    installer.AddLibrary(dlib)

if myenv["tests"]:
    testenv = myenv.Copy()
    # AddCasaTests()  move the code belowto tools/casa.py
    # gather test files
    # SGlob works in build dir, so only for cc files
    tests = testenv.SGlob("test/*.cc")
    tests += testenv.SGlob("*/test/*.cc")
    # point to tests local includes
    testenv.AppendUnique(LIBPATH=[testenv["BUILDDIR"]])
    testenv.Prepend(LIBS=[libname])
    # store CPPPATH, to reset after each test 
    cpppath = testenv["CPPPATH"]
    # install assay *.run *.in* *.out files into test directory
    # use glob here with an absolute path, as Sconsript is "called" 
    # from the build dir.
    testaux = glob.glob("%s/%s/test/*.*" % (rootdir, testenv["PACKAGE"]))
    testaux += glob.glob("%s/%s/*/test/*.*" % (rootdir, testenv["PACKAGE"]))
    # exclude cc files
    testaux = [ i for i in testaux if not i.endswith('.cc') ]
    testaux = [ i for i in testaux if not i.endswith('.h') ]
    tdir = Dir("#/tests").abspath
    for i in testaux:
	# Copy doesn't overwrite, so check if they already exist 
	# from a previous run.
	if not os.path.exists(tdir):
	    testenv.Execute(Mkdir(tdir))
	outfile = os.path.join(tdir, os.path.basename(i))
	if not os.path.exists(outfile):
	    testenv.Execute(Copy(outfile, i))
 
    for i in tests:
	testenv["CPPPATH"] = cpppath
	# get the basename no suffix of the file
	tinfile = os.path.splitext(os.path.basename(i))[0]
	tdir = os.path.split(i)[0]
	# include location of test headers
	testenv.AppendUnique(CPPPATH=[tdir])			
	# out put gos into the root/test directory
	toutfile = os.path.join("#","tests", "_"+tinfile+".so")
	tapp = testenv.LoadableModule(toutfile, source=i)

# install headers, only works with absolute dir.
installer.AddHeaders( os.path.join(rootdir,"pyrap"), "*.h", "pyrap", True )
installer.AddHeaders( os.path.join(rootdir,"pyrap"), "*.tcc", "pyrap", True )
